using System.Collections;
using NodeCanvas.Variables;
using UnityEngine;

namespace NodeCanvas.BehaviourTrees
{
	[AddComponentMenu("")]
	[Name("Filter")]
	[Category("Decorators")]
	[Description("Filters the access of it's child node either a specific number of times, or every specific amount of time. By default the node is 'Treated as Inactive' to it's parent when child is Filtered. Unchecking this option will instead return Failure when Filtered.")]
	[Icon("Lock")]
	public class BTFilter : BTDecorator
	{
		public enum LimitMode
		{
			LimitNumberOfTimes = 0,
			CoolDown = 1
		}

		public LimitMode limitMode = LimitMode.CoolDown;

		public BBInt maxCount = new BBInt
		{
			value = 1
		};

		public BBFloat coolDownTime = new BBFloat
		{
			value = 5f
		};

		public bool inactiveWhenLimited = true;

		private int executedCount;

		private float currentTime;

		public override void OnGraphStarted()
		{
			executedCount = 0;
			currentTime = 0f;
		}

		protected override Status OnExecute(Component agent, Blackboard blackboard)
		{
			if (base.decoratedConnection == null)
			{
				return Status.Resting;
			}
			if (limitMode == LimitMode.CoolDown)
			{
				if (currentTime > 0f)
				{
					return inactiveWhenLimited ? Status.Resting : Status.Failure;
				}
				base.status = base.decoratedConnection.Execute(agent, blackboard);
				if (base.status == Status.Success || base.status == Status.Failure)
				{
					StartCoroutine(Cooldown());
				}
			}
			else if (limitMode == LimitMode.LimitNumberOfTimes)
			{
				if (executedCount >= maxCount.value)
				{
					return inactiveWhenLimited ? Status.Resting : Status.Failure;
				}
				base.status = base.decoratedConnection.Execute(agent, blackboard);
				if (base.status == Status.Success || base.status == Status.Failure)
				{
					executedCount++;
				}
			}
			return base.status;
		}

		private IEnumerator Cooldown()
		{
			currentTime = coolDownTime.value;
			while (currentTime > 0f)
			{
				currentTime -= Time.deltaTime;
				yield return null;
			}
		}
	}
}
